package com.heima.canal.freemarker;

import com.heima.dfs.api.ApArticleContentFeign;
import com.heima.dfs.api.UploadFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.util.HashMap;
import java.util.Map;

@Component
public class ArticlePageHandler {
    @Autowired
    private Configuration configuration;
    @Autowired
    private UploadFeign uploadFeign;
    @Autowired
    private ApArticleContentFeign apArticleContentFeign;


    /**
     * 文章生成
     */
    public void article(ApArticle apArticle) throws Exception {
        //获取模板
        Template template = configuration.getTemplate("article.ftl");
        //准备数据模型
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("apArticle", apArticle);
        //调用leadnews-article查询article_content
        Long id = apArticle.getId();
        ApArticleContent apArticleContent = apArticleContentFeign.contentText(id);

        dataMap.put("apArticleContent", apArticleContent);

        //通过Template合成数据模型，并输出新文件（文章详情页）
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataMap);
        //将文件写入dfs
        ResponseResult responseResult = uploadFeign.uploadHtml(content);
        String url = (String) responseResult.getData();
        apArticleContentFeign.updateContentUrl(url, id);
        System.out.println(url);
    }

}
